﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using FastReflectionLib;
using JSZS.API;
using Newtonsoft.Json;
using JSZS.Data;
using System.Data;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Configuration;
using System.IO;

using System.Xml;
using System.Threading.Tasks;
using Newtonsoft.Json.Converters;

namespace JSZS.API
{
    public class JSZSManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, QJY_User UserInfo)
        {
            MethodInfo methodInfo = typeof(JSZSManage).GetMethod(msg.Action.ToUpper());
            JSZSManage model = new JSZSManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });
        }

        public void ADDKC(HttpContext context, Msg_Result msg, string P1, string P2, QJY_User UserInfo)
        {
            QJY_KeChen kcmodel = JsonConvert.DeserializeObject<QJY_KeChen>(P1);
            if (kcmodel.ID == 0)
            {
                kcmodel.CRDate = DateTime.Now;
                kcmodel.CRUser = UserInfo.ID.ToString();
                new QJY_KeChenB().Insert(kcmodel);
            }
            else
            {
                new QJY_KCJHB().Delete(d => d.KCID == kcmodel.ID);
                new QJY_KCDataB().Delete(d => d.KCID == kcmodel.ID);
                new QJY_KeChenB().Update(kcmodel);
            }

            List<QJY_KCJH> kcjh = JsonConvert.DeserializeObject<List<QJY_KCJH>>(kcmodel.Remark);
            foreach (QJY_KCJH model in kcjh)
            {
                model.CRUser = UserInfo.ID.ToString();
                model.CRDate = DateTime.Now;
                model.KCID = kcmodel.ID;
                new QJY_KCJHB().Insert(model);

                //生成课程日历数据
                //1.根据周数计算实际开始时间
                //1.1实际上课日期和开课日期相差几天
                int durDays = model.Week.Value - (int)kcmodel.StartDate.Value.DayOfWeek;
                if (durDays < 0)//间隔<0，说明开课和实际上课时间不在一周，+7天
                {
                    durDays += 7;
                }
                DateTime startD = kcmodel.StartDate.Value.AddDays(durDays);

                while (startD <= kcmodel.EndDate.Value)
                {
                    int TID = Int32.Parse(model.CRUser);
                    int h = Int32.Parse(model.SKHour);
                    int m = Int32.Parse(model.SKMinute);
                    int l = Int32.Parse(model.KCLength);

                    QJY_KCData kcd = new QJY_KCData();
                    kcd.KCID = kcmodel.ID;
                    kcd.TeacherID = TID;
                    kcd.SKDate = startD.AddHours(h).AddMinutes(m);
                    kcd.SKHour = model.SKHour;
                    kcd.SKMinte = model.SKMinute;
                    kcd.KCLength = model.KCLength;
                    kcd.CRUser = model.CRUser;
                    kcd.CRDate = DateTime.Now;
                    kcd.Week = model.Week;
                    kcd.ENDate = startD.AddHours(h).AddMinutes(m + l);

                    new QJY_KCDataB().Insert(kcd);

                    //1.2添加7天，第二周的上课时间
                    startD = startD.AddDays(7);
                }
            }



        }

        //
        public void GETKCDATA(HttpContext context, Msg_Result msg, string P1, string P2, QJY_User UserInfo)
        {
            //默认本周
            DateTime now = DateTime.Now;
            if (P1 != "") //传本周最后一天日期
            {
                now = DateTime.Parse(P1);
                if (P2 != "")
                {
                    //nxt：下一周日历，pre：上一周日历
                    if (P2 == "nxt")
                    {
                        now = now.AddDays(1);
                    }
                    else if (P2 == "pre")
                    {
                        now = now.AddDays(-13);
                    }
                }
            }

            now = DateTime.Parse(now.ToString("yyyy-MM-dd"));

            int month = now.Month;
            int week = CommonHelp.WeekOfMonth(now, 1);
            DateTime wkFirst = CommonHelp.FirstWeekDayOfPreviousDate(now);//本周第一天
            DateTime wkEnd = CommonHelp.LastWeekDayOfPreviousDate(now);   //本周最后一天

            KC_KCDATA kc = new KC_KCDATA();
            kc.month = month;
            kc.week = week;
            kc.weekFirst = wkFirst;
            kc.weekEnd = wkEnd;

            for (int i = 0; i <= 6; i++)
            {
                KC_WKDate kd = new KC_WKDate();
                kd.wkDate = wkFirst.AddDays(i);
                kd.wk = i + 1;
                if ((i + 1) == 7)
                {
                    kd.wk = 0;//周日:0
                }
                kd.wkName = CommonHelp.WeekName(i + 1);
                kc.weekDate.Add(kd);
            }
            //按照时间段，看周一到周日有什么课程，8，12，14,16

            DataTable dtKC = new QJY_KCDataB().GetDTByCommand(string.Format("select D.*,C.KCName,C.Class,C.StartDate,C.EndDate from QJY_KCData D join QJY_KeChen C on D.KCID=C.ID WHERE D.CRUser=" + UserInfo.ID + " and D.SKDate>='{0}' and D.SKDate<='{1}' ", wkFirst.ToString("yyyy-MM-dd"), wkEnd.ToString("yyyy-MM-dd")));
            List<KC_KCWEEK> kcwList = new List<KC_KCWEEK>();

            //设置显示的时间段8-18
            Dictionary<string, string> timeRange = new Dictionary<string, string>();
            timeRange.Add("8", "0-10"); //0-10
            timeRange.Add("10", "10-12");
            timeRange.Add("12", "12-16");
            timeRange.Add("16", "16-24");

            foreach (var vt in timeRange)
            {
                KC_KCWEEK kcw = new KC_KCWEEK();
                kcw.time = vt.Key;

                int st = Int32.Parse(vt.Value.Split('-')[0]);
                int et = Int32.Parse(vt.Value.Split('-')[1]);

                DataView dv = new DataView(dtKC);
                for (int i = 1; i <= 7; i++)
                {
                    var ndS = wkFirst.AddDays((i - 1)).AddHours(st); //时间段开始时间
                    var ndE = wkFirst.AddDays((i - 1)).AddHours(et).AddMinutes(-1); //结束时间

                    dv.RowFilter = "SKDate>='" + ndS.ToString("yyyy-MM-dd HH:mm:ss") + "' and SKDate<='" + ndE.ToString("yyyy-MM-dd HH:mm:ss") + "' and week=" + (i == 7 ? 0 : i);
                    kcw.weekKC.Add(dv.ToTable());
                }

                kcwList.Add(kcw);
            }

            kc.kcData = kcwList;

            msg.Result = kc;
        }
        

        /// <summary>
        /// 课程日历数据结构
        /// </summary>
        private class KC_KCDATA
        {
            public int month { get; set; }
            public int week { get; set; }
            public DateTime weekFirst { get; set; }//本周第一天
            public DateTime weekEnd { get; set; }  //本周最后一天

            public List<KC_WKDate> weekDate = new List<KC_WKDate>();
            public dynamic kcData { get; set; }
        }

        //日期数据
        private class KC_WKDate
        {
            public DateTime wkDate { get; set; }
            public int wk { get; set; }
            public string wkName { get; set; }
        }
        private class KC_KCWEEK
        {
            public string time { get; set; }
            public List<object> weekKC = new List<object>();
        }
        
    }
}